package cn.angis.quartz.service;

import cn.angis.common.constant.ScheduleConstants;
import cn.angis.common.exceprion.TaskException;
import cn.angis.db.service.BaseService;
import cn.angis.quartz.dto.input.JobInput;
import cn.angis.quartz.dto.output.JobOutput;
import cn.angis.quartz.mapper.JobMapper;
import cn.angis.quartz.model.SysJob;
import cn.angis.quartz.util.CronUtils;
import cn.angis.quartz.util.ScheduleUtils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import java.util.List;

/**
 * 定时任务调度表服务
 *
 * @author angis.cn
 * @Date 2025-06-04
 */
@Component
public class JobService extends BaseService<JobMapper, SysJob> {

    @Inject
    private Scheduler scheduler;

    @Init
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> jobList = baseMapper.all();
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Transaction
    public int pauseJob(String id) throws SchedulerException {
        SysJob job = getById(id);
        String jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = update(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Transaction
    public int resumeJob(String id) throws SchedulerException {
        SysJob job = getById(id);
        String jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = update(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Transaction
    public int deleteJob(String id) throws SchedulerException {
        SysJob job = getById(id);
        String jobId = job.getId();
        String jobGroup = job.getJobGroup();
        int rows = delete(id);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Transaction
    public void deleteJobByIds(String[] jobIds) throws SchedulerException {
        for (String jobId : jobIds) {
            deleteJob(jobId);
        }
    }

    @Transaction
    public int changeStatus(JobInput job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job.getId());
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job.getId());
        }
        return rows;
    }

    @Transaction
    public boolean run(String id) throws SchedulerException {
        SysJob job = getById(id);
        boolean result = false;
        String jobId = job.getId();
        String jobGroup = job.getJobGroup();
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, job);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    @Transaction
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = save(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    @Transaction
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = getById(job.getId());
        int rows = update(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        String jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }

    public List<JobOutput> list(JobInput jobInput) {
        return baseMapper.selectList(jobInput);
    }

}